<template>
  <div class="infoList">
    <div class="add">
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item>
          <el-button type="primary" @click="addOne" round>增加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="compPage" border style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="姓名" align="center">
      </el-table-column>
      <el-table-column prop="age" label="年龄" align="center">
      </el-table-column>
      <el-table-column prop="sex_text" label="性别" align="center">
      </el-table-column>
      <el-table-column prop="father" label="父亲姓名" align="center">
      </el-table-column>
      <el-table-column prop="mather" label="母亲姓名" align="center">
      </el-table-column>
      <el-table-column prop="reginTime" label="入校时间" align="center">
      </el-table-column>
      <el-table-column prop="address" label="家庭住址" align="center">
      </el-table-column>
      <el-table-column prop="phone" label="联系方式" align="center">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <!-- slot-scope="scope" 中的scope能够拿到这一行和这一列的数据, 注意需要写在template上 -->
        <template slot-scope="scope">
          <el-button
            type="warning"
            icon="el-icon-edit-outline"
            @click="editeOne(scope.row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="deleteOne(scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- destroy-on-close 为true时表示关闭时清空dialog -->
    <el-dialog
      :title="state ? '添加数据' : '修改数据'"
      :visible.sync="dialogFormVisible"
      width="600px"
      destroy-on-close
    >
      <el-form :model="changeDataForm" :rules="rules" ref="changeForm">
        <el-form-item label="姓名" label-width="100px" prop="name">
          <el-input
            v-model.trim="changeDataForm.name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="年龄" label-width="100px" prop="age">
          <el-input
            v-model.trim="changeDataForm.age"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" label-width="100px" prop="sex" align="left">
          <template>
            <el-radio v-model="changeDataForm.sex" label="1">男</el-radio>
            <el-radio v-model="changeDataForm.sex" label="2">女</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="父亲姓名" label-width="100px" prop="father">
          <el-input
            v-model.trim="changeDataForm.father"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="母亲姓名" label-width="100px" prop="mather">
          <el-input
            v-model.trim="changeDataForm.mather"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="入校时间"
          label-width="100px"
          prop="reginTime"
          align="left"
        >
          <el-date-picker
            v-model="changeDataForm.reginTime"
            align="center"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="家庭住址" label-width="100px" prop="address">
          <el-input
            v-model.trim="changeDataForm.address"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系方式" label-width="100px" prop="phone">
          <el-input
            v-model.trim="changeDataForm.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit('changeForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>

    <PagingDevice
      :currentPage="condition.page"
      :pagesize="condition.pagesize"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
// import { getInfoList, changeInfoItem, deleteInfoItem } from "@/api/api";
import PagingDevice from "@/components/common/PagingDevice.vue";
import { getTableData, changeTableData, deleteTableData } from "@/utils/table";
import pageDeviceMixin from "@/mixins/pageDeviceMixin"; // 里面包含了分页的需要的方法和变量和计算属性

export default {
  mixins: [pageDeviceMixin],
  components: {
    PagingDevice,
  },
  data() {
    return {
      tableData: [],
      dialogFormVisible: false,
      state: true, // true为添加数据，false为修改数据
      changeDataForm: {
        // 修改数据需要用到的对象绑定
        name: "",
        age: "",
        sex: "1",
        father: "",
        mather: "",
        reginTime: "",
        address: "",
        phone: "",
      },
      curChangeRow: {}, // 当前正在被修改的行原数据, 用来校验修改前后是否有发生改变
      rules: {
        name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" },
          // { type: "number", message: "必须是数字型", trigger: "blur" },
        ],
        sex: [{ required: true, message: "性别不能为空", trigger: "blur" }],
        reginTime: [
          { required: true, message: "时间不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "家庭住址不能为空", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
        ],
      },
      loading: false, // 是否在加载页面, 加入loading的目的是提供一个遮盖层，比如删除数据时希望删除成功后渲染结束后才能继续删除下一个
      // 时间快捷选项需要配置的
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            },
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            },
          },
        ],
      },
    };
  },
  methods: {
    async getData() {
      const res = await getTableData(this, "/info"); // 这里需要注意的是由于getTableData是异步方法，那么它的返回值也应该会是Promise(不管这个返回值数据的类型是什么)
      this.tableData = res.data;
      this.total = res.total;
    },
    async deleteOne({ id }) {
      this.loading = true;
      const res = await deleteTableData(this, "/info", id);
      if (res.status == 200) {
        let currentTotalPage = Math.ceil(
          (this.total - 1) / this.condition.size
        ); // 向上取整就能得到总页数, this.total - 1 这里删除成功后要先减一，因为这里的total还没有更新需要手动减一
        if (
          this.condition.page > currentTotalPage &&
          this.condition.page != 1
        ) {
          // 如果当前页数大于总页数，说明最后一页的数据全部删除完毕了, 让当前页跳到上一页, 并且当前也不能为1，不然的话它会停留在已经没有数据的那一页
          this.condition.page--;
        }
        this.getData(); // 重新渲染
      }
      // 防止它再删除后为渲染时又继续点击了
      setTimeout(() => {
        this.loading = false;
      }, 200);
    },
    editeOne(row) {
      this.dialogFormVisible = true;
      this.state = false;
      this.curChangeRow = row; // 当前正在改变和行
      this.changeDataForm = { ...row }; // 结构出一个新对象赋值给它，而不是让它指向那一行的row，否则会出现修改表单时row的数据也跟着变化, row这里是有id传过来的
    },
    addOne() {
      // 添加时 重置 changeDataForm 数据，防止编辑后的遗留
      this.changeDataForm = {
        name: "",
        age: "",
        sex: "1",
        father: "",
        mather: "",
        reginTime: "",
        address: "",
        phone: "",
      };
      this.state = true;
      this.dialogFormVisible = true;
    },
    // 修改和增加数据的提交
    async onSubmit(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (
            JSON.stringify(this.curChangeRow) ==
            JSON.stringify(this.changeDataForm)
          ) {
            this.$message({
              type: "warning",
              message: "未对数据做修改",
            });
            this.dialogFormVisible = false; // 隐藏dialog
            return;
          }
          let method = this.state ? "post" : "put";
          await changeTableData(this, "/info", method, this.changeDataForm); // 异步的方法所以需要await以下，不然的话不会及时更新getData
          this.getData();
          this.dialogFormVisible = false;
        }
      });
    },
  },
  created() {
    this.getData();
  },
};
</script>

<style lang="scss" scoped>
.add {
  // text-align: right;
  .el-button {
    width: 300px;
  }
}
</style>
